<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible"
    @close="closeDlg()"
    width="1000px"
    destroy-on-close
  >
    <el-row :gutter="20" class="wrapperSon">
      <el-col>
        产线名称:
      </el-col>
      <el-col>{{ this.queryConditions.currentProduceLineName }}</el-col>
      <el-col>排产周期:</el-col>
      <el-col
        >{{ this.queryConditions.produceYear }}年{{
          this.queryConditions.produceMonthStr
        }}</el-col
      >
      <el-col>工序选择:</el-col>
      <el-col
        ><el-Select
          v-model="temp.procedureId"
          placeholder="请选择工序"
          @change="handleProcedureSelectChange"
        >
          <el-Option
            v-for="itm in this.queryConditions.lstProcedures"
            :label="itm.procedureName"
            :value="itm.id"
            :key="itm.id"
          ></el-Option> </el-Select
      ></el-col>
      <el-col style="float:right;"
        ><el-button type="primary" icon="el-icon-d-arrow-right">同步前周期配置</el-button></el-col
      >
    </el-row>
    <el-row type="flex" justify="start" :gutter="30">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          align="center"
          label="工序名称"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.procedureName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产线ID" width="95" v-if="false">
          <template slot-scope="scope">
            {{ scope.row.produceLineId }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备ID" width="95" v-if="false">
          <template slot-scope="scope">
            {{ scope.row.deviceId }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="设备编号"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.deviceNo }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="设备类型id"
          width="95"
          v-if="false"
        >
          <template slot-scope="scope">
            {{ scope.row.deviceTypeId }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="设备类型"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.deviceTypeName }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="工序ID" width="95" v-if="false">
          <template slot-scope="scope">
            {{ scope.row.procedureId }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="已用设备数量"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.usedDeviceAmount }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="已用设备负荷率"
          width="110"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.usedDeviceLoadFactor }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="剩余设备数量"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.unusedDeviceAmount }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="总负荷率"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.totalDeviceLoadFactor }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="人员比例" width="95">
          <template slot-scope="scope">
            {{ scope.row.employeeRatio }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="已用人员数量" width="95">
          <template slot-scope="scope">
            {{ scope.row.usedEmployeeAmount }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="剩余人员数量"
          width="95"
          style="display:none;"
        >
          <template slot-scope="scope">
            {{ scope.row.unusedEmployeeAmount }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="总人员负荷率"
          width="95"
          v-if="false"
        >
          <template slot-scope="scope">
            {{ scope.row.totalEmployeeLoadFactor }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="产线编号"
          width="95"
          v-if="false"
        >
          <template slot-scope="scope">
            {{ scope.row.produceLineNo }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="日历名称" width="95">
          <template slot-scope="scope">
            {{ scope.row.calendarName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备配置" width="95">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.deviceAmount"
              placeholder="请输入设备数量"
              @input="handleEditChange(scope.$index, scope.row, 1)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="人员配置" width="95">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.employeeAmount"
              placeholder="请输入人员数量"
              @input="handleEditChange(scope.$index, scope.row, 2)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="日历配置" width="95">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.calendarId"
              placeholder="请选择日历"
              @change="handleCalendarSelChange(scope.$index,scope.row)"
            >
              <el-option
                v-for="itm in lstCalendars"
                :label="itm.label"
                :value="itm.value"
                :key="itm.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        :page-sizes="listQuery.pageSizes"
        @pagination="fetchData"
      />
    </el-row>
    <el-row class="wrapperSon">
      <el-col :span="6"></el-col>
      <el-col :span="6" style="text-align:center;"
        ><el-button type="primary" width="25%" @click="ui_update()">
          保存
        </el-button></el-col
      >
      <el-col :span="6" style="text-align:center;">
        <el-button width="200px" @click="dialogFormVisible = false">
          取消
        </el-button></el-col
      >
      <el-col :span="6"></el-col>
    </el-row>   
  </el-dialog>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
  initDeviceResource,
  updateBatch
} from "@/api/produce/schedulePlan/ProduceLinePlanResourceApi";
import moment, { duration } from "moment";
import objectUtil from "@/utils/objectUtil";
import { getProcedureDeviceCapacity } from "@/api/device/mesDevice";
import { getAll as getAllCalendar } from "@/api/produce/ProduceCalendarApi";

export default {
  name: "producelineresourcesetdlg",
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"  
      };
      return statusMap[status];
    }
  },
  props: {
    dialogVisible: false,
    input: {}
  },
  watch: {
    dialogVisible: function(newValue, oldValue) {
      if (newValue != null) {
        this.dialogFormVisible = newValue;
        if (newValue) {
          this.fetchData();
          this.getProcedureDeviceCapacity();
        }
      }
    },
    input: function(newValue, oldValue) {
      //判断两个对象是否相等
      if (objectUtil.isObjectChangedSimple(oldValue, newValue)) {
        this.queryConditions = { ...newValue };
        if (
          this.queryConditions.lstProcedures != null &&
          this.queryConditions.lstProcedures.length > 0 &&
          this.queryConditions.lstProcedures[0].id != 0
        ) {
          this.queryConditions.lstProcedures.splice(0, 0, {
            id: 0,
            procedureName: "请选择"
          });
          this.getProcedureDeviceCapacity();
        }
        this.fetchData();
      }
    },
    deep: true
  },
  data() {
    return {
      listSon: [],
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        pageSizes: [10, 20, 30]
      },
      currentProcedureId: 0,
      dialogFormVisible: false,
      dialogStatus: "create",
      textMap: {
        update: "添加订单",
        create: "配置资源"
      },
      //表格變量
      lstSelected: [],
      queryConditions: {
        produceYear: 0,
        produceMonth: 0,
        produceMonthStr: "",
        currentProduceLineId: 0, //当前产线
        currentProduceLineNo: "",
        currentProduceLineName: "",
        lstProcedures: [], //所有工序
        currentMontWorkHours: 0, //当前月的工作小时数
        totalPlanAmount: 0 //计划总产量
      },
      deliveryDates: [],
      temp: {
        id: undefined,
        produceLineId: "",
        deviceId: "",
        deviceNo: "",
        deviceTypeId: "",
        deviceTypeName: "",
        employeeRatio: "",
        procedureId: 0,
        procedureNo: "",
        usedDeviceAmount: "",
        usedDeviceLoadFactor: "",
        unusedDeviceAmount: "",
        totalDeviceLoadFactor: "",
        usedEmployeeAmount: "",
        unusedEmployeeAmount: "",
        totalEmployeeLoadFactor: "",
        produceLineNo: "",
        produceLineName: "",
        procedureName: "",
        produceYear: 0,
        produceMonth: 0,
        calengdarId: 0, //日历ID
        calendarName: ""
      },
      lstProcedureDeviceCapacities: [], //工序设备生产率
      lstCalendars: [] //所有日历
    };
  },
  computed: {},
  created() {
    //如果产线还没有分配资源
    if (
      this.queryConditions.currentProduceLineId > 0 &&
      this.queryConditions.lstProcedures != null &&
      this.queryConditions.lstProcedures.length > 0
    ) {
      this.fetchData(this.queryConditions);
    }
    //查询所有的生产日历
    this.getAllCalendars();
  },
  methods: {
    resetTemp() {
      this.temp = {
        id: undefined,
        produceLineId: "",
        deviceId: "",
        deviceNo: "",
        deviceTypeId: "",
        deviceTypeName: "",
        employeeRatio: "",
        procedureId: 0,
        procedureNo: "",
        usedDeviceAmount: "",
        usedDeviceLoadFactor: "",
        unusedDeviceAmount: "",
        totalDeviceLoadFactor: "",
        usedEmployeeAmount: "",
        unusedEmployeeAmount: "",
        totalEmployeeLoadFactor: "",
        produceLineNo: "",
        produceLineName: "",
        procedureName: "",
        produceYear: 0,
        produceMonth: 0,
        calengdarId: 0, //日历ID
        calendarName: ""
      };
    },
    handleSelectionChange(val) {
      this.lstSelected = val;
      const type = this.list.find(v => v.therbligsNo === val.therbligsNo);
      if (type != null) {
        this.currentSaleOrderMstTypeId = type.id;
      }
    },
    fetchData() {
      let params = {
        page: this.listQuery.page,
        size: this.listQuery.limit,
        produceLineId: this.queryConditions.currentProduceLineId,
        procedureId: this.temp.procedureId,
        produceYear: this.queryConditions.produceYear,
        produceMonth: this.queryConditions.produceMonth
      };
      return getList(params).then(response => {
        if (response.data.records != null) {
          this.list = response.data.records;
          this.list.forEach(v => {
            v.deviceAmount = 0;
            v.employeeAmount = 0;
          });
          // console.log(this.list);
          this.total = response.data.total;
          this.listLoading = false;
        }
      });
    },
    getProcedureDeviceCapacity() {
      let p = {
        procedureIds: this.queryConditions.lstProcedures
          .filter(v => v.id > 0)
          .map(v => {
            return v.id;
          }),
        deviceId: 0
      };
      if (p.procedureIds == null || p.procedureIds.length <= 0) return;
      //传递数组
      getProcedureDeviceCapacity(p).then(response => {
        if (response.data != null) {
          this.lstProcedureDeviceCapacities = response.data;
        }
      });
    },
    rowClick(row, column, event) {
      // this.currentSaleOrderMstTypeId = row.id;
      // this.fetchData();
    },
    handleProcedureSelectChange(val) {
      this.fetchData();
    },
    handleSelect(val) {
      this.queryConditions.orderNo = val.value;
    },
    handleInput(val) {
      this.queryConditions.orderNo = val;
    },
    closeDlg() {
      this.dialogFormVisible = false;
      this.$emit("hideResourceDlg", this.dialogFormVisible);
    },
    //处理输入框change事件
    ui_update() {
      updateBatch(this.list).then(response => {
        this.$message.success("更新成功!");
        this.dialogFormVisible = false;
        //更新主页面的负荷率？
        this.$emit("updateFactor", this.list);
      });
    },
    handleEditChange(index, row, type) {
      if (type == 1) {
        //设备
        if (!/^[0-9]\d*$/.test(row.deviceAmount)) {
          this.$message.error("请输入不小于零的整数!");
          row.deviceAmount = 0;
          return;
        }
        let oldAmount = this.list[index].usedDeviceAmount;
        if (row.deviceAmount > row.unusedDeviceAmount + oldAmount) {
          this.$message.error("设备数量不能超过剩余数量!");
        }

        this.list[index].usedDeviceAmount = parseInt(row.deviceAmount);
        //先根据比例计算人员分配数据
        this.list[index].employeeAmount =
          parseInt(row.deviceAmount) * parseInt(row.employeeRatio);

        //计算剩余设备数量
        this.calculateUnusedDeviceAmount(
          row.deviceId,
          parseInt(row.deviceAmount) - oldAmount
        );
        debugger;
        let normalAmount = this.getProcedureNormalDeviceAmount(
          row.procedureId,
          row.deviceId
        );

        //计算负荷率
        this.list[index].usedDeviceLoadFactor = parseFloat(
          normalAmount / parseFloat(this.list[index].usedDeviceAmount)
        ).toFixed(2);
        let oldItem = this.list[index];
        this.list.splice(index, 1, oldItem);
      } //人员
      else {
        if (!/^[0-9]\d*$/.test(row.employeeAmount)) {
          this.$message.error("请输入不小于零的整数!");
          row.employeeAmount = 0;
          return;
        }
        let oldAmount = this.list[index].usedEmployeeAmount;
        if (row.employeeAmount > row.unusedEmployeeAmount + oldAmount) {
          this.$message.error("人员数量不能超过剩余数量!");
        }

        this.list[index].usedEmployeeAmount = parseInt(row.employeeAmount);
        this.calculateUnusedEmployeeAmount(
          row.deviceId,
          parseInt(row.employeeAmount) - oldAmount
        );
        let normalAmount = (this.list[
          index
        ].totalEmployeeLoadFactor = parseFloat(
          normalAmount / parseFloat(this.list[index].usedEmployeeAmount)
        ).toFixed(2));
        let oldItem = this.list[index];
        this.list.splice(index, 1, oldItem);
      }
    },

    //获取的某工序的产能
    getProcedureNormalDeviceAmount(procedureId, deviceId) {
      let deviceCount = 0;
      let itm = this.lstProcedureDeviceCapacities.find(
        v => v.procedureId == procedureId && v.deviceId == deviceId
      );
      if (itm != null) {
        deviceCount = Math.ceil(
          this.queryConditions.totalPlanAmount /
            parseFloat(
              (this.queryConditions.currentMontWorkHours /
                itm.productivitySpeed) *
                itm.productivityQuantity
            )
        );
      }
      return deviceCount;
    },
    //同类设备计算剩余数量
    calculateUnusedDeviceAmount(deviceId, allocateAmount) {
      this.list.forEach(v => {
        if (v.deviceId == deviceId) {
          v.unusedDeviceAmount -= allocateAmount;
        }
      });
    },
    //获得同类人员剩余数量
    calculateUnusedEmployeeAmount(deviceId, allocateAmount) {
      this.list.forEach(v => {
        if (v.deviceId == deviceId) {
          v.unusedEmployeeAmount -= allocateAmount;
        }
      });
    },
    getAllCalendars() {
      getAllCalendar().then(response => {
        if (response.data != null && response.data.length > 0) {
          response.data.forEach(v => {
            this.lstCalendars.push({
              label: v.calendarName,
              value: v.id
            });
          });
           this.lstCalendars.splice(0,0,{
              label: "请选择",
              value: 0
            });
        }
      });
    },
    handleCalendarSelChange(index, row) {
      //设置列表的日历ID,并触发更新
      debugger
      let oldItem = this.list[index];
      oldItem.calendarId = row.calendarId;
      let item = this.lstCalendars.find(v => v.value == row.calendarId);
      if (item != null) {
        oldItem.calendarName = item.label;
      }
      this.list.splice(index, 1, oldItem);
    }
  }
};
</script>
<style scoped>
.item1 {
  margin-top: 20px;
}
.wrapperSon {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.app-container {
  padding: 0;
}
</style>
